<template>
    <div class="container">
        <el-tabs type="border-card" class="tabs" @tab-change="changeTab" v-model="activeName">
            <el-tab-pane name="all">
                <template #label>
                    <span class="custom-tabs-label">
                        <el-icon>
                            <calendar />
                        </el-icon>
                        <span>全部</span>
                    </span>
                </template>
                <el-scrollbar max-height="calc(100vh - 50px)">
                    <ul ref="itemList" class="item-list">
                        <li v-for="person in allList" :key="person._id" class="person-item">
                            <BirthdayItem v-if="!person.category || person.category == 0" :person="person"
                                @loadData="loadAllData" @editData="editData(person)" @deleteData="deleteData(person)"
                                @itemClick="itemClick(person)" />
                            <MemorialDayItem v-else-if="person.category == 1" :person="person" @loadData="loadAllData"
                                @editData="editData(person)" @deleteData="deleteData(person)"
                                @itemClick="itemClick(person)" />
                            <CountdownDayItem v-else-if="person.category == 2" :person="person" @loadData="loadAllData"
                                @editData="editData(person)" @deleteData="deleteData(person)"
                                @itemClick="itemClick(person)" />
                        </li>
                    </ul>
                </el-scrollbar>
            </el-tab-pane>
            <el-tab-pane name="birthday">
                <template #label>
                    <span class="custom-tabs-label">
                        <el-icon>
                            <calendar />
                        </el-icon>
                        <span>生日</span>
                    </span>
                </template>
                <el-scrollbar max-height="calc(100vh - 50px)">
                    <ul class="item-list">
                        <li v-for="person in birthdayList" :key="person._id" class="person-item">
                            <BirthdayItem :person="person" @loadData="loadAllData" @editData="editData(person)"
                                @deleteData="deleteData(person)" @itemClick="itemClick(person)" />
                        </li>
                    </ul>
                </el-scrollbar>
            </el-tab-pane>
            <el-tab-pane name="memorialday">
                <template #label>
                    <span class="custom-tabs-label">
                        <el-icon>
                            <calendar />
                        </el-icon>
                        <span>纪念日</span>
                    </span>
                </template>
                <el-scrollbar max-height="calc(100vh - 50px)">
                    <ul class="item-list">
                        <li v-for="person in memorialDayList" :key="person._id" class="person-item">
                            <MemorialDayItem :person="person" @loadData="loadAllData" @editData="editData(person)"
                                @deleteData="deleteData(person)" @itemClick="itemClick(person)" />
                        </li>
                    </ul>
                </el-scrollbar>
            </el-tab-pane>
            <el-tab-pane name="countdownday">
                <template #label>
                    <span class="custom-tabs-label">
                        <el-icon>
                            <calendar />
                        </el-icon>
                        <span>倒数日</span>
                    </span>
                </template>
                <ul class="item-list">
                    <li v-for="person in countdownDayList" :key="person._id" class="person-item">
                        <CountdownDayItem :person="person" @loadData="loadAllData" @editData="editData(person)"
                            @deleteData="deleteData(person)" @itemClick="itemClick(person)" />
                    </li>
                </ul>
            </el-tab-pane>
        </el-tabs>

        <el-dropdown style="display: flex;">
            <span class="add-button">
                +
            </span>
            <template #dropdown>
                <el-dropdown-menu>
                    <el-dropdown-item @click="addBirthday">生日</el-dropdown-item>
                    <el-dropdown-item @click="addMemorialDay" divided>纪念日</el-dropdown-item>
                    <el-dropdown-item @click="addCountdownDay" divided>倒数日</el-dropdown-item>
                </el-dropdown-menu>
            </template>
        </el-dropdown>

        <el-dialog v-model="birthdayEditor" :title="title" width="500" destroy-on-close>
            <BirthdayEditor @cancel="birthdayEditor = false" @submit="handleSubmit" :person="person"
                :category="category" />
        </el-dialog>

        <el-drawer v-model="showDetail" :with-header="true" size="60%" destroy-on-close="true">
            <template #header="{ titleId, titleClass }">
                <h1 :id="titleId" :class="titleClass">{{ detailTitle }}</h1>
            </template>
            <BirthdayDetail :formData="detailData" />
        </el-drawer>
    </div>
</template>

<script setup>
import { reactive, ref, computed } from 'vue'
import BirthdayEditor from './BirthdayEditor.vue'
import BirthdayItem from './BirthdayItem.vue'
import BirthdayDetail from './BirthdayDetail.vue'
import MemorialDayItem from './MemorialDayItem.vue'
import CountdownDayItem from './CountdownDayItem.vue'
import birthdayUtil from '../utils/birthdayUtil';
import { Calendar } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Sortable from 'sortablejs';

const birthdayEditor = ref(false);
const allList = reactive([]);
const birthdayList = reactive([]);
const memorialDayList = reactive([]);
const countdownDayList = reactive([]);
const person = ref({});
const detailData = ref({});
const showDetail = ref(false);
const state = ref('add');
const category = ref(0);
const categoryName = ['生日', '纪念日', '倒数日'];
const title = computed(() => {
    return (state.value === 'add' ? '新增' : '编辑') + categoryName[category.value]
});
const activeName = ref('all');
const detailTitle = ref('日期详情');
const itemList = ref(null);
let sortable;

// 监听主题切换
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
    const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches
    document.documentElement.classList.toggle('dark', isDark)
})

utools.onPluginEnter(({ code, type, payload, option }) => {
    // 支持拖拽排序
    sortable = Sortable.create(itemList.value, {
        animation: 150,       // 拖拽动画时长（毫秒）
        // handle: '.drag-handle',
        onEnd: (event) => {
            // 获取拖拽前后的索引
            const { oldIndex, newIndex } = event;

            // 更新数组顺序，只支持全部排序
            const movedItem = allList.splice(oldIndex, 1)[0];
            allList.splice(newIndex, 0, movedItem);
            // 重新生成排序号
            allList.forEach((item, index) => {
                item.sort = index;
                const newItem = {...item};
                utools.db.put(newItem); // 更新数据库中的排序号
            });

            birthdayList.length = 0;
            memorialDayList.length = 0;
            countdownDayList.length = 0;
            birthdayList.push(...loadData(allList, null, 0));
            memorialDayList.push(...loadData(allList, null, 1));
            countdownDayList.push(...loadData(allList, null, 2));
        }
    });
    console.log('sortable', sortable);
    // 是否暗黑模式
    const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches
    document.documentElement.classList.toggle('dark', isDark)

    // 子输入框搜索
    utools.setSubInput(({ text }) => {
        loadAllData(text);
    }, '搜索名称')

    // 打开小生日进行提醒
    const dataList = utools.db.allDocs('birthday');
    for (let data of dataList) {
        let untilDays = birthdayUtil.daysUntilBirthday(data.birthday, data.dateType);
        if (untilDays == 0) {
            let message;
            if (data.category == 0) {
                message = `今天是【${data.name}】的生日！要送上祝福哦！`;
            } else if (data.category == 1) {
                message = `今天是【${data.name}】纪念日！`;
            } else if (data.category == 2) {
                message = `今天是【${data.name}】倒数日！`;
            }
            utools.showNotification(message);
        }
    }

    // 切换页签
    if (payload === '小生日') {
        activeName.value = 'all';
    } else if (payload === '生日') {
        activeName.value = 'birthday';
    } else if (payload === '纪念日') {
        activeName.value = 'memorialday';
    } else if (payload === '倒数日') {
        activeName.value = 'countdownday';
    }

    loadAllData();
})

function changeTab(tab) {
 
}

// 加载数据
function loadAllData(text) {
    const dataList = utools.db.allDocs('birthday');

    allList.length = 0;
    birthdayList.length = 0;
    memorialDayList.length = 0;
    countdownDayList.length = 0;

    allList.push(...loadData(dataList, text, null));
    birthdayList.push(...loadData(dataList, text, 0));
    memorialDayList.push(...loadData(dataList, text, 1));
    countdownDayList.push(...loadData(dataList, text, 2));

    // 搜索时禁用拖拽排序
    if(text) {
        sortable.option("disabled", true);
    } else {
        sortable.option("disabled", false);
    }
}

// 加载数据
function loadData(dataList, searchText, category) {
    // 过滤数据列表
    const filterList = dataList.filter(data => {
        const nameMatch = !searchText || data.name.includes(searchText);
        const categoryMatch = category === null || data.category === category;
        return nameMatch && categoryMatch;
    });

    // 如果有过滤结果，先按排序字段排序，如果没有排序字段则按照创建时间排序
    if (filterList.length > 0) {
        filterList.sort((a, b) => {
            if (a.sort !== undefined && b.sort !== undefined) {
                return a.sort - b.sort;
            }
            return new Date(a.createTime) - new Date(b.createTime);
        });
    }

    return filterList;
}

// 提交回调
function handleSubmit() {
    loadAllData();
    birthdayEditor.value = false;
    utools.setSubInputValue('')
}

// 编辑回调
function editData(data) {
    state.value = 'edit';
    category.value = data.category;
    person.value = data;
    birthdayEditor.value = true;
}

// 点击列表项
function itemClick(data) {
    detailData.value = data;
    showDetail.value = true;
    if (data.category == 0) {
        detailTitle.value = '生日详情';
    } else if (data.category == 1) {
        detailTitle.value = '纪念日详情';
    } else if (data.category == 2) {
        detailTitle.value = '倒数日详情';
    }
}

// 删除数据
function deleteData(person) {
    ElMessageBox.confirm(
        '确认删除该记录吗?',
        '删除确认',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        window.utools.db.remove(person._id);
        ElMessage.success('删除成功！');
        loadAllData();
    });
}

// 新增生日
function addBirthday() {
    state.value = 'add';
    category.value = 0;
    person.value = null;
    birthdayEditor.value = true;
}

// 新增纪念日
function addMemorialDay() {
    state.value = 'add';
    person.value = null;
    category.value = 1;
    birthdayEditor.value = true;
}

// 新增倒数日
function addCountdownDay() {
    state.value = 'add';
    person.value = null;
    category.value = 2;
    birthdayEditor.value = true;
}
</script>

<style scoped>
.container {
    /* max-width: 100%; */
    margin: 0 auto;
}

.tabs {
    height: calc(100vh);
    /* overflow-y: hidden; */
}

.el-tabs--border-card {
    border: 0px;
    /* background-color: transparent; */
}

:deep(.tabs>.el-tabs__content) {
    padding: 5px;
}

:deep(.tabs .custom-tabs-label .el-icon) {
    vertical-align: middle;
}

:deep(.tabs .custom-tabs-label span) {
    vertical-align: middle;
    margin-left: 4px;
}

:deep(.container>.el-dropdown) {
    display: none;
}

.item-list {
    padding: 0 10px 0 10px;
}

.person-item {
    display: flex;
    /* flex-direction: column; */
    /* justify-content: center; */
    /* align-items: center; */
    margin-bottom: 10px;
}

.add-button {
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 50px;
    height: 50px;
    background-color: #007bff;
    color: white;
    border-radius: 50%;
    font-size: 24px;
    text-align: center;
    line-height: 50px;
    cursor: pointer;
}
</style>